package com.example.codeservice.controller;

import com.example.codeservice.service.CodeService;
import com.example.codeservice.service.EmailServiceFeignClient;
import com.example.codeservice.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhouyp
 * @program example-parent
 * @description
 * @create 2020-07-27
 */
@RestController
@RequestMapping("/api/code")
public class CodeController {

	@Autowired
	private CodeService codeService;

	@Autowired
	private UserServiceFeignClient userServiceFeignClient;

	@Autowired
	private EmailServiceFeignClient emailServiceFeignClient;

	@RequestMapping("/create/{email}")
	public boolean create(@PathVariable String email) {
		System.out.println("create执行，email：" + email);
		//查询邮箱是否注册过
		boolean registered = userServiceFeignClient.isRegistered(email);
		if (registered) {
			System.out.println("邮箱已经注册过，email：" + email);
			//已经注册过
			return false;
		}
		System.out.println("邮箱未注册过，email：" + email);
		//生成验证码
		String code = codeService.createCode(email);
		if (null == code || code.length() != 6) {
			//验证码生成失败
			return false;
		}
		System.out.println("生成验证码，email：" + email + "；code：" + code);

		//发送验证码邮件
		return emailServiceFeignClient.sendEmail(email, code);
	}

	@RequestMapping("/validate/{email}/{code}")
	public int validate(@PathVariable String email,
	                    @PathVariable String code) {
		return codeService.validate(email, code);
	}
}
